package com.cyou.qb.common.service.impl;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.cyou.nad.dao.PojoPage;
import com.cyou.nad.datastore.query.JdbcPage;
import com.cyou.nad.datastore.query.JdbcPageDao;
import com.cyou.qb.common.dao.ActiveDao;
import com.cyou.qb.common.dao.AwardDao;
import com.cyou.qb.common.dao.JiuGongGeDao;
import com.cyou.qb.common.dao.PayLogDao;
import com.cyou.qb.common.domain.Active;
import com.cyou.qb.common.domain.PayLog;
import com.cyou.qb.common.domain.QiangbaAdmin;
import com.cyou.qb.common.service.ActivityService;
import com.cyou.qb.exception.ServiceException;

@Service("ActivityServiceImpl")
public class ActivityServiceImpl extends BaseSerivceImpl implements ActivityService {

	private Log log = LogFactory.getLog(getClass());

	@Autowired
	private JdbcPageDao jdbcPageDao;
	@Autowired
	private ActiveDao activeDao;
	@Autowired
	private PayLogDao payLogDao;

	/**
	 * @author zoudongchao
	 */
	@Override
	public Active findActivity(int activeId) {
		return activeDao.findActiveById(activeId);
	}

	/**
	 * Description 保存一个活动
	 * @author lidongwei
	 * @throws Exception 
	 * @throws IOException 
	 * @since 2012-9-23 下午10:01:08
	 * @see TODOsome class
	 */
	@Override
	public int saveOneActivity(String activeName, String gameCode, String gameName, String gameType, String gameComOp,
			String gameComRd, String gameChannel, String gameNet, String gameBBS, String gameDown, String image1,
			String image2, String image2Link, String startTime, String endTime, String memo, String introduce,
			int adminId, String rule) throws Exception {
		//将string类型的时间转换为date类型
		Date startDate = new Date();
		startDate = DateUtils.parseDate(startTime.trim(), (new String[] { "yyyy-MM-dd HH:mm:ss" }));
		Date endDate = new Date();
		endDate = DateUtils.parseDate(endTime.trim(), (new String[] { "yyyy-MM-dd HH:mm:ss" }));
		
		if(startDate.after(endDate)||startDate.equals(endDate)){
			throw new ServiceException("添加的开始时间不能晚于或等于结束时间");
		}
		//对introduce处理
//		introduce = htmlspecialchars(introduce);
		Active active = new Active();
		active.setActiveName(activeName);
		active.setGameCode(gameCode);
		active.setGameName(gameName);
		active.setGameType(gameType);
		active.setGameComOp(gameComOp);
		active.setGameComRd(gameComRd);
		active.setGameChannel(gameChannel);
		active.setGameNet(gameNet);
		active.setGameBBS(gameBBS);
		active.setGameDown(gameDown);
		active.setImage1(image1);
		active.setImage2(image2);
		active.setImage2Link(image2Link);
		active.setStartTime(startDate);
		active.setEndTime(endDate);
		active.setMemo(memo);
		active.setIntroduce(introduce);
		active.setAdminId(adminId);
		active.setRule(rule);//rule不会为空，最差为"{}"
		active.setStatus(1);//初始状态为开启
		active.setPublish(0);//初始状态未发布
		active.setgMax(0);//初始金额为0
		active.setFaceNum(-1);//初始商城通讯id为-1
		active.setCreateDate(new Date());
		//写入数据库
		activeDao.saveOneActivity(active);
		getServiceContext().addLog(active.getActiveName(), active.getId(), "t_active", "添加活动", new Object[]{active}, null);
		return 0;
	}

	/**
	 * Description 删除活动
	 * @author lidongwei
	 * @throws Exception 
	 * @since 2012-9-23 下午10:01:08
	 * @see TODOsome class
	 */
	@Override
	public int removeActivity(String activityId) throws Exception {
		
		Active active = activeDao.findActiveById(Integer.valueOf(activityId));//先获取active，然后进行set
		if (active != null) {
			if(active.getStatus()==1&&(active.getPublish()==0 || active.getStartTime().after(new Date()))){//只有未开始的可以被删除
				active.setStatus(0);
				activeDao.updateOneActive(active);
				getServiceContext().addLog(active.getActiveName(), active.getId(), "t_active", "删除活动", new Object[]{0}, new Object[]{1});
			}
		}else {
			throw new ServiceException("数据库出错，找不到活动");
		}
		//需要填写log日志
		return 0;
	}

	/**
	 * Description 获取活动分页
	 * @author lidongwei
	 * @throws Exception 
	 * @since 2012-9-23 下午10:01:08
	 * @see TODOsome class
	 */
	@Override
	public JdbcPage findPageQueryActivity(QiangbaAdmin admin,String state, String activityType, String activityName, int pageNo, int pageSize) throws Exception {

		/**
		 * select distinct act.id,act.image1,act.name as activeName,act.start_time as startTime,act.end_time as endTime,
			act.publish,act.game_type as gameType,adm.login_name as createPeople,g.gnum as costG,act.status as status, 
			case when awardS.active_id is null then  -1 else  awardS.active_id end awardStatus,
			case  WHEN  ((act.publish = 0 or act.start_time > now()) and act.status=1 ) then 1 WHEN act.status=2 THEN 4 when  (act.start_time <= now() and act.end_time >= now() and act.publish=1 and act.status=1) then 2 when (act.end_time < now() and act.publish = 1 and act.status=1) then 3 else -1 end faceStatus 
			from t_sys_admin adm,t_active act 
			LEFT  JOIN 
			(select maxNum.id as gid , (maxNum.gnum -   
			(case   when   sumNum.gnum   is   null    
			then  0  
			else  sumNum.gnum   
			end )) as gnum 
			from  
			(select act.id as id , act.g_max as gnum 
			from  t_active act) as maxNum 
			LEFT  JOIN 
			(select awa.active_id as gid ,(SUM(awa .g_num*awa .max_num)) as gnum 
			from t_award awa 
			where awa.type=3  
			group by awa.active_id) as sumNum 
			ON maxNum.id=sumNum.gid)    g  
			ON  g.gid=act.id      
			LEFT JOIN
			(select  *    from t_award  where
			exists( 
			select * from t_jiu_gong_ge where t_jiu_gong_ge.award_id=t_award.id
			)  
			and  t_award.valid=1) awardS
			ON  act.id=awardS.active_id
			where 1=1 and act.status!=0  and act.admin_id = adm.id  
		 */
		String sql = "select distinct act.id,act.image1,act.name as activeName,act.start_time as startTime,act.end_time as endTime,"
					+" act.publish,act.game_type as gameType,adm.login_name as createPeople,g.gnum as costG,act.status as status, "
					+" case when awardS.active_id is null then  -1 else  awardS.active_id end awardStatus,"
					+" case  WHEN  ((act.publish = 0 or act.start_time > ?) and act.status=1 ) then 1 WHEN act.status=2 THEN 4 when  (act.start_time <= ? and act.end_time >= ? and act.publish=1 and act.status=1) then 2 when (act.end_time < ? and act.publish = 1 and act.status=1) then 3 else -1 end faceStatus "
					+" from t_sys_admin adm,t_active act "
					+" LEFT  JOIN "
					+" (select maxNum.id as gid , (maxNum.gnum -   "
					+" (case   when   sumNum.gnum   is   null    "
					+" then  0  "
					+" else  sumNum.gnum   "
					+" end )) as gnum "
					+" from  "
					+" (select act.id as id , act.g_max as gnum "
					+" from  t_active act) as maxNum "
					+" LEFT  JOIN "
					+" (select awa.active_id as gid ,(SUM(awa .g_num*awa .max_num)) as gnum "
					+" from t_award awa "
					+" where awa.type=3  "
					+" group by awa.active_id) as sumNum "
					+" ON maxNum.id=sumNum.gid)    g  "
					+" ON  g.gid=act.id      "
					+" LEFT JOIN"
					+" (select  *    from t_award  where"
					+" exists( "
					+" select * from t_jiu_gong_ge where t_jiu_gong_ge.award_id=t_award.id"
					+" )  "
					+" and  t_award.valid=1) awardS"
					+" ON  act.id=awardS.active_id"
					+" where 1=1 and act.status!=0  and act.admin_id = adm.id  ";
							
		List<Object> param = new ArrayList<Object>();
		Date now = new Date();
		param.add(now);
		param.add(now);
		param.add(now);
		param.add(now);
		if (StringUtils.isNotBlank(state)) {
			
			if ("1".equals(state)) {//尚未开始。只要（未发布， 或者时间未到），并且开启
				sql += " and (act.publish = 0 or act.start_time > ?) and act.status=1 ";
				param.add(now);
			} else if ("2".equals(state)) {//正在进行 在时间中并且发布，开启
				sql += " and act.start_time <= ? and act.end_time >= ? and act.publish=1 and act.status=1";
				param.add(now);
				param.add(now);

			} else if ("3".equals(state)) {//已经结束 时间超过，发布，开启
				sql += " and act.end_time < ? and act.publish = 1 and act.status=1";
				param.add(now);
			} else if ("4".equals(state)) {//关闭
				sql += " and act.status=2";
			}
		}

		if (StringUtils.isNotBlank(activityType)) {
			sql += " and act.game_type like ? ";
			param.add("%" + activityType + "%");
		}
		if (StringUtils.isNotBlank(activityName)) {
			sql += " and act.name like ? ";
			param.add("%" + activityName + "%");

		}
		
		if(admin.getStatus()==1&&admin.getValid()==1){
			if(admin.getType().equals("1")){
				sql += " and act.admin_id = ? ";
				param.add(admin.getAdminId());
			}
		}else{
			throw new ServiceException("该用户无权查看");
		}
		sql+=" order by  act.create_date desc";
		return jdbcPageDao.pageQuery(sql, pageNo, pageSize, param.toArray());
	}
	public void setJdbcPageDao(JdbcPageDao jdbcPageDao) {
		this.jdbcPageDao = jdbcPageDao;
	}

	public void setActiveDao(ActiveDao activeDao) {
		this.activeDao = activeDao;
	}

	/**
	 * Description 进行修改
	 * @author lidongwei
	 * @throws Exception 
	 * @since 2012-9-29 下午5:30:49
	 * @see TODOsome class
	 */
	@Override
	public int updateOneActivity(String activeId, String activeName, String gameCode, String gameName, String gameType,
			String gameComOp, String gameComRd, String gameChannel, String gameNet, String gameBBS, String gameDown,
			String image1, String image2, String image2Link, String startTime, String endTime, String memo,
			String introduce, String rule) throws Exception {
		Date startDate = new Date();
		startDate = DateUtils.parseDate(startTime.trim(), (new String[] { "yyyy-MM-dd HH:mm:ss" }));
		Date endDate = new Date();
		endDate = DateUtils.parseDate(endTime.trim(), (new String[] { "yyyy-MM-dd HH:mm:ss" }));
		Active active = activeDao.findActiveById(Integer.valueOf(activeId));//先获取active，然后进行set
		if (active != null) {
			Active oldActive = active; 
			active.setActiveName(activeName);
			active.setGameCode(gameCode);
			active.setGameName(gameName);
			active.setGameType(gameType);
			active.setGameComOp(gameComOp);
			active.setGameComRd(gameComRd);
			active.setGameChannel(gameChannel);
			active.setGameNet(gameNet);
			active.setGameBBS(gameBBS);
			active.setGameDown(gameDown);
			active.setImage1(image1);
			active.setImage2(image2);
			active.setImage2Link(image2Link);
			active.setStartTime(startDate);
			active.setEndTime(endDate);
			active.setMemo(memo);
			active.setIntroduce(introduce);
			active.setRule(rule);
			activeDao.updateOneActive(active);
			getServiceContext().addLog(active.getActiveName(), active.getId(), "t_active", "修改活动", new Object[]{active}, new Object[]{oldActive});
		} else {
			throw new ServiceException("数据库出错，找不到活动");
		}
		return 0;
	}

	/**
	 * Description 发布活动
	 * @author lidongwei
	 * @throws Exception 
	 * @since 2012-10-5 下午4:47:49
	 * @see TODOsome class
	 */
	@Override
	public void updatePublishAcitivity(String activityId) throws Exception {
		Active active = activeDao.findActiveById(Integer.valueOf(activityId));//先获取active，然后进行set
		if (active != null) {
			//在九宫格且配置,有奖品
			 String sql  = "select count(*)  from t_award  where"
					+ " exists( "
					+ " select * from t_jiu_gong_ge where t_jiu_gong_ge.award_id=t_award.id"
					+ " )  "
					+ " and t_award.active_id=? and  t_award.valid=1";
			 List<Object> param = new ArrayList<Object>();
			 param.add(Integer.valueOf(activityId));
			int finishAwardCount = (jdbcPageDao.query(sql, param.toArray())).getInt(0, 0);
			if(active.getEndTime().before(new Date())||!(active.getStatus()==1&&active.getPublish()==0)||finishAwardCount<=0){
				throw new ServiceException("未满足发布条件，不能发布");
			}
			else{
				active.setPublish(1);
				activeDao.updateOneActive(active);
			}
		}else {
			throw new ServiceException("数据库出错，找不到活动");
		}
		
	}

	/**
	 * 判断活动是否可以预览
	 * @param activityId
	 * @return
	 * @throws Exception
	 */
	public boolean checkPreview(int activityId) throws Exception{
		
		String sql  = "select count(*)  from t_award  where"
				+ " exists( "
				+ " select * from t_jiu_gong_ge where t_jiu_gong_ge.award_id=t_award.id"
				+ " )  "
				+ " and t_award.active_id=? and  t_award.valid=1";
		List<Object> param = new ArrayList<Object>();
		param.add(Integer.valueOf(activityId));
		int finishAwardCount = (jdbcPageDao.query(sql, param.toArray())).getInt(0, 0);
		
		return (finishAwardCount > 0);
	}
	/**
	 * Description 开启或关闭活动
	 * @author lidongwei
	 * @throws Exception 
	 * @since 2012-10-6 上午11:30:52
	 * @see TODOsome class
	 */
	@Override
	public void updateCloseOpenActivity(String activityId) throws Exception {
		Active active = activeDao.findActiveById(Integer.valueOf(activityId));//先获取active，然后进行set
		if (active != null) {
			int status = active.getStatus();
			if(1==status){
				active.setStatus(2);
				activeDao.updateOneActive(active);
				getServiceContext().addLog(active.getActiveName(), active.getId(), "t_active", "开启或关闭活动", new Object[]{(status==1)?2:1}, new Object[]{status});
			}
			else if(2==status){
				active.setStatus(1);
				String sql  = "select count(*)  from t_award  where"
							+ " exists( "
							+ " select * from t_jiu_gong_ge where t_jiu_gong_ge.award_id=t_award.id"
							+ " )  "
							+ " and t_award.active_id=? and  t_award.valid=1";
				List<Object> param = new ArrayList<Object>();
				param.add(Integer.valueOf(activityId));
				int finishAwardCount = (jdbcPageDao.query(sql, param.toArray())).getInt(0, 0);
				if(active.getEndTime().before(new Date())||!(active.getPublish()==1)||finishAwardCount<=0){
					throw new ServiceException("未满足开启条件，不能开启");
				}else{
					activeDao.updateOneActive(active);
					getServiceContext().addLog(active.getActiveName(), active.getId(), "t_active", "开启或关闭活动", new Object[]{(status==1)?2:1}, new Object[]{status});
				}
			}
			else
			{
				throw new ServiceException("数据库出错，活动状态出错");
			}
			
			
			
		}else {
			throw new ServiceException("数据库出错，找不到活动");
		}
	}

	/**
	 * Description 充值
	 * @author lidongwei
	 * @throws Exception 
	 * @since 2012-10-6 下午1:13:45
	 * @see TODOsome class
	 */
	@Override
	public void updateRechargeGold(String acId,String gbNum,String accID,int accountId) throws Exception {
		
		Active active = activeDao.findActiveById(Integer.valueOf(acId));
		
		if (active != null) {
			long allG = (long)active.getgMax()+(long)Integer.valueOf(gbNum);
			if(allG>2147483647){
				throw new ServiceException("累计充值金额超过2147483647");
			}else{
				Active oldAct  = active;
				active.setgMax((active.getgMax()+Integer.valueOf(gbNum)));
				active.setFaceNum(Integer.valueOf(accID));
				activeDao.updateOneActive(active);
				getServiceContext().addLog(active.getActiveName(), active.getId(), "t_active", "活动充值--改变数量", new Object[]{active}, new Object[]{oldAct});
				//填写充值流水
				PayLog payLog = new PayLog();
				payLog.setActiveTid(Integer.valueOf(acId));
				payLog.setAdminId(accountId);
				payLog.setCreateDate(new Date());
				payLog.setNum(Integer.valueOf(gbNum));
				payLogDao.saveOnePayLog(payLog);
				getServiceContext().addLog(active.getActiveName(), active.getId(), "t_active", "活动充值--充值流水", new Object[]{payLog}, null);
			
			}
			
		}else {
			throw new ServiceException("数据库出错，找不到活动");
		}
		
	}

	/**
	 * Description
	 * @author lidongwei
	 * @since 2012-10-7 下午2:33:39
	 * @see TODOsome class
	 */
	@Override
	public int findFaceStatus(String activityId) {
		Active active = activeDao.findActiveById(Integer.valueOf(activityId));
		if(active != null){
			Date now = new Date();
			if((0==active.getPublish()||active.getStartTime().after(new Date()))&&1==active.getStatus()){
				return 1;
			}else if((now.after(active.getStartTime())|| now.equals(active.getStartTime())) && (now.equals(active.getEndTime()) || now.before(active.getEndTime())) && 1==active.getPublish() && 1==active.getStatus()){
				return 2;
			}else if(now.after(active.getEndTime()) && 1==active.getPublish() && 1==active.getStatus()){
				return 3;
			}else if(2==active.getStatus()){
				return 4;
			}
				
		}
		return 0;
	}

	@Override
	public PojoPage<Active> pageQuery(String oderBy,int pageNo, int pageSize) {
		return activeDao.pageQuery(oderBy, pageNo, pageSize);
	}

	@Override
	public List<Active> findAllActive() {
		return activeDao.finAllActive();
	}

	@Override
	public List<Active> findEndedActivity(int days) {
		return activeDao.findEndedActivity(days);
	}

	@Override
	public int updateActiveDrawNum(int id, long drawTimes) {
		return activeDao.updateActiveDrawNum(id, drawTimes);
	}
	/**
	 * 为了在页面上显示<> & \ 暂时未利用
	 * Description
	 * @author lidongwei
	 * @since 2012-10-30
	 */
	private String htmlspecialchars(String str) {
		str = str.replaceAll("&", "&amp;");
		str = str.replaceAll("<", "&lt;");
		str = str.replaceAll(">", "&gt;");
		str = str.replaceAll("\"", "&quot;");
		return str;
	}


}
